package csc.daonjpa.java.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import csc.daonjpa.java.dao.AccountDAO;
import csc.daonjpa.java.dao.CustomerDAO;
import csc.daonjpa.java.domain.Account;

/**
 * This is a controller for home page when user first accesses the application
 * 
 * @author nvu3
 * 
 */

@Controller
public class HomeController {
	
	@RequestMapping(value = "/login")
	public String doLoginCustomer(HttpServletRequest request, Model model) {
		// Read account info from request and save into Account object
		String loginId = request.getParameter("loginId");
		String password = request.getParameter("password");
		CustomerDAO cusDAO = new CustomerDAO();

		if (cusDAO.checkLogin(loginId, password)) {
			System.out.println(" login ok!!!");

			return ("forward:/setSession.html");
		} else {
			System.out.println(" login failed!!!");
			return ("loginFailed");
		}
	}
	@RequestMapping(value = "/home")
	public ModelAndView getAccountList(HttpServletRequest request, Model model) {
		// Create a new AccountDAO
		AccountDAO accountDao = new AccountDAO();
		ModelAndView model1 = new ModelAndView("home");
		List<Account> accountList = null;
		String loginId = request.getSession().getAttribute("loginSession")
				.toString();
		accountList= accountDao.getAccounts(loginId);
		// Get the list of all accounts from DB
		try {
			
			model.addAttribute("listAccount", accountList);
			return model1;
		} catch (Exception e) {
			model1.addObject("ERROR_CODE", "You get error");
			model.addAttribute("listAccount", accountList);
			return model1;

		}
		// Add the list of accounts to request object which will be then used in
		// jsp to show to user

	}

}
